/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package protovitae.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

/**
 *
 * @author Ryan J. Bovorasmy
 */
public class OrganismTree extends DefaultTreeModel {
    
    public OrganismTree(TreeNode root) {
        super(root);
    }
    
    public int getIndexOfChild(Object parent, Object child) {
        this.orderChildren(parent);
        return super.getIndexOfChild(parent, child);
    }

    public Object getChild(Object parent, int index) {
        this.orderChildren(parent);
        return super.getChild(parent, index);
    }

    /**
     * Orders the children of a DefaultMutableTreeNode
     * @param parent
     */
    private void orderChildren(Object parent) {
        if (parent == null) {
            return;
        }

        if (parent instanceof DefaultMutableTreeNode) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) parent;
            ArrayList children = Collections.list(node.children());
            Collections.sort(children);
            System.out.println("Im being used.");
            node.removeAllChildren();
            Iterator childrenIterator = children.iterator();
            while (childrenIterator.hasNext()) {
                node.add((DefaultMutableTreeNode) childrenIterator.next());
            }
        }
    }
}
